% by YLX  
% 2021/6/11
% Version 2.3
% change log 
%% added timing function 
%% passed test

addpath functions;
% Global Variables are avaliable for ALL FUNCTIONS
% >>> global variables settings
global P J I ci cI r LAMBDA
P = [.1, .5, .9]; % for test only
LAMBDA = 3;
ci=40;cI=200;r=100;
J = 3; I = 8;
% end global settings <<<

clockToStamp = @(clk) clk(end) + 60*clk(end-1) + 3600*clk(end-2);
% this function transfers clock value to seconds 
% etc. clock = [Year, Month, Day, Hour, Minute, Second] variavle saving current time
% etc. clock = [2021, 6, 11, 0, 58, 55.1]
% etc. clockToStamp(clock) = 3600*0 + 58*60 + 55.1 

% Line = xlsread('Simulated.xlsx'); 
% Line = load('sim_data.mat');
load('j_all.mat');
Line = j_all;
patient_number = sum(Line > 0); % equivalent to size(2)

S = zeros(I, J);
% Profit = zeros(patient_number, I); % For What?

init_time = clockToStamp(clock); % set main clock

best_is = zeros(1, patient_number);
sum_profits = zeros(1,patient_number+1);
for n = 1:patient_number

    fprintf("Arranging Patient No. %d \n", n);
    start_time = clockToStamp(clock); % set loop clock

    j = Line(n);
    profits = zeros(1, I);
    for i = 1:I
        S_test = S;
        S_test(i, j) = S_test(i, j) + 1; % Replace rim & rimS
        Q = findQ(S_test); % size(Q) = [I, max_m]
        R = findR(S_test, Q);
        profits(i) = function_fQR(Q, R);
    end
    i = find(profits == max(profits));
    sum_profits(n+1) = max(profits) + sum_profits(n);
    best_is(n) = i(1);
    i = i(1);
    S(i, j) = S(i, j) + 1;
    Q = findQ(S);
    R = findR(S, Q);

    fprintf("    Time = %.2f seconds \n\n", clockToStamp(clock)-start_time);
    
end
sum_profits = sum_profits(2:end);
    

fprintf("\n\n Totle Time = %.1f seconds \n", clockToStamp(clock)-init_time);

display(S)
display(best_is)
load('arangement_i_paper');
display(arangement_i_paper)

plot(1:patient_number,sum_profits);
